package com.kk.xhr.model.service.impl;

import com.kk.xhr.common.pojo.BinaryEnum;
import com.kk.xhr.model.assembler.LevelStructKit;
import com.kk.xhr.model.dao.LevelDynamicSqlSupport;
import com.kk.xhr.model.dao.LevelMapper;
import com.kk.xhr.model.dto.LevelDTO;
import com.kk.xhr.model.entity.Level;
import com.kk.xhr.model.service.ILevelService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.kk.xhr.common.RedisConstant.LEVEL_CACHE;
import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;

/**
 * 职称服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/3/4
 * @since 1.0.0
 */
@Repository
@RequiredArgsConstructor
@CacheConfig(cacheNames = LEVEL_CACHE)
public class LevelServiceImpl implements ILevelService {
    private final LevelMapper levelMapper;
    private final LevelStructKit instance = LevelStructKit.INSTANCE;

    @Override
    public List<LevelDTO> query() {
        return levelMapper.select(dsl -> dsl
            .where(LevelDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue())))
            .stream()
            .map(instance::toDto)
            .collect(Collectors.toList());
    }

    @Override
    @Cacheable(key = "#id")
    public Optional<LevelDTO> queryById(Long id) {
        return levelMapper.selectOne(dsl -> dsl
            .where(LevelDynamicSqlSupport.id, isEqualTo(id))
            .and(LevelDynamicSqlSupport.status, isEqualTo(BinaryEnum.TRUE.getValue())))
            .map(instance::toDto);
    }

    @Override
    public boolean add(LevelDTO dto) {
        if (null == dto.getLevel()) {
            return false;
        }
        return 1 == levelMapper.insertSelective(instance.toEntity(dto));
    }

    @Override
    @CacheEvict(key = "#p0.id")
    public boolean modify(LevelDTO dto) {
        if (null == dto.getId()) {
            return false;
        }
        return 1 == levelMapper.updateByPrimaryKeySelective(instance.toEntity(dto));
    }

    @Override
    @CacheEvict(key = "#id")
    public boolean modifyStatus(Long id, BinaryEnum status) {
        if (null == status) {
            return false;
        }
        return 1 == levelMapper.updateByPrimaryKeySelective(new Level().withId(id).withStatus(status.getValue()));
    }
}
